import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { environment } from '../../../../environments/environment';
import { LoginModel } from '../../../models/auth.model';
import { Router } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AppRoutingModule } from '../../../app-routing.module';
import {LabelValue} from "../../../components/select/normal-select/normal-select.component";

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
    loadingState: boolean;
    dataForm: FormGroup;
    login: LoginModel =
        {
            username: environment.login.userName,
            password: environment.login.password,
            grantType: 'password',
        } as LoginModel;
    img: any = '';
    tenantList: LabelValue[]=[];
    selectedTenant: string = '';
    constructor(
        private _formBuilder: FormBuilder,
        private _router: Router,
        private authService: AuthService,
        private msg: NzMessageService,
        private appRouterModule: AppRoutingModule,
    ) {
        this.dataForm = this._formBuilder.group({
            userName: ['', [Validators.required]],
            password: ['', [Validators.required]],
            captcha: ['', [Validators.required]]
        });
    }

    ngOnInit() {
        this.getCode();
        this.getTenantList();
    }

    getTenantList() {
        this.tenantList = [];
            this.authService.getTenantList().subscribe(res => {
            if (res.success) {
                res.data.voList.forEach(item => {
                    this.tenantList.push({
                        label: item.companyName,
                        value: item.tenantId
                    })
                });
            }
        })
    }

    /**
     * 登录验证
     */
    onLoginValid() {
        this.loadingState = true;
        this.login.tenantId = this.selectedTenant;
        this.authService.authLogin(this.login).subscribe(
            res => {
                if (res.code == 200){
                    this.appRouterModule.initUserMenus();
                    this._router.navigateByUrl('manage').then();
                }else {
                    this.getCode();
                }
            }
        ).add(()=>{
            this.loadingState = false;
        });
    }

    /**
     * 获取验证码
     */
    getCode() {
        this.authService.captchaImage().subscribe(res => {
            if (res.success) {
                this.img ="data:image/gif;base64,"+ res.data.img;
                this.login.uuid = res.data.uuid;
            }else{
                this.msg.error(res.msg);
            }
        })
    }
}
